/**
 * Copyright &copy; 2012-2016 <a href="https://git.oschina.net/zdw2016/webbase5">Webbase</a> All rights reserved.
 */
package com.foreveross.webbase.demo.web;

import java.util.Date;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.foreveross.webbase.common.config.Global;
import com.foreveross.webbase.common.persistence.Page;
import com.foreveross.webbase.common.utils.StringUtils;
import com.foreveross.webbase.common.web.BaseController;
import com.foreveross.webbase.demo.entity.Demo;
import com.foreveross.webbase.demo.service.DemoService;

@Controller
@RequestMapping(value = "${adminPath}/demo")
public class DemoController extends BaseController {

	@Autowired
	private DemoService demoService;

	@RequiresPermissions("demo:Demo:list")
	@RequestMapping(value = { "list", "" })
	public String list(Demo demo) {
		Page<Demo> page = demoService.findPage(new Page<Demo>(request(), response()), demo);
		attr("page", page);
		return "demo/demo-list";
	}

	@RequiresPermissions("demo:Demo:form")
	@RequestMapping("form")
	public String form(String id) {
		if (StringUtils.isNotEmpty(id)) {
			Demo demo = demoService.get(id);
			attr("demo", demo);
		} else {
			attr("demo", new Demo());
		}
		return "demo/demo-form";
	}

	@RequiresPermissions("demo:Demo:add")
	@RequestMapping("add")
	public String add(Demo demo, RedirectAttributes redirectAttributes) {
		//Subject subject = SecurityUtils.getSubject();
		try {
			if (demo.getIsNewRecord()) {
				demo.setCreatetime(new Date());
				demoService.save(demo);
				addMessage(redirectAttributes, "保存Demo成功");
				}
		} catch (Exception e) {
			addMessage(redirectAttributes, "保存Demo失败");
		}
		return "redirect:" + Global.getAdminPath() + "/demo/?repage";
	}

	
	@RequiresPermissions("demo:Demo:update")
	@RequestMapping("update")
	public String update(Demo demo, RedirectAttributes redirectAttributes) {
		//Subject subject = SecurityUtils.getSubject();
		try {
			if (!demo.getIsNewRecord()) {
				demoService.save(demo);
				addMessage(redirectAttributes, "保存Demo成功");
			}
		} catch (Exception e) {
			addMessage(redirectAttributes, "保存Demo失败");
		}
		return "redirect:" + Global.getAdminPath() + "/demo/?repage";
	}

	
	@RequiresPermissions("demo:Demo:delete")
	@RequestMapping("delete")
	public String delete(@RequestParam String id, RedirectAttributes redirectAttributes) {

		demoService.delete(id);
		addMessage(redirectAttributes, "删除Demo成功");
		return "redirect:" + Global.getAdminPath() + "/demo/?repage";
	}
}